package in.muton.edushare.documentModel.excel;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class SimpleExcelDocument {
	
	private static final int MAX_COLUMNS_FOR_CONTENT_FIT = 100;
	private HSSFWorkbook workbook;
	private HSSFSheet sheet;
	private List<AbsTable> tableList;
	private StylePalette stylePalette;

	public SimpleExcelDocument(String sheetName) {
		this.workbook = new HSSFWorkbook();
		this.sheet = workbook.createSheet(sheetName);
		this.tableList = new ArrayList<AbsTable>();
		this.stylePalette = new StylePalette(workbook);
	}
	
	public SimpleExcelDocument(){
		this("sheet1");
	}

	public void append(AbsTable absTable) {
		this.tableList.add(absTable);
	}
	
	public byte[] getWorkbookAsByteArray(){
		return getWorkbookAsByteArray(false);
	}
	
	/** very expensive and slow */
	public byte[] getWorkbookAsByteArray(boolean setColumnWidthToContent){
		
		//make content fit columns *very slow*
		for(int i=0; i < MAX_COLUMNS_FOR_CONTENT_FIT; i++){
			sheet.autoSizeColumn(i);
		}
		
		//write to outstream
		byte[] byteBook = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			workbook.write(out);
			byteBook = out.toByteArray();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return byteBook;
	}
	
	public List<AbsTable> getTables(){
		return this.tableList;
	}
	
	public HSSFSheet getSheet(){
		return this.sheet;
	}
	
	public HSSFWorkbook getWorkbook(){
		return this.workbook;
	}
	
	public StylePalette getStylePalette(){
		return this.stylePalette;
	}

}
